<template>
  <div class="articlePublic">
    <!-- 面包糠 -->
    <el-breadcrumb separator="/" class="mianbaoxie">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item
        ><a href="/index/articlePublic" style="cursor: pointer"
          >文章发布</a
        ></el-breadcrumb-item
      >
      <el-breadcrumb-item
        ><a href="/index/articleList" style="cursor: pointer"
          >文章列表</a
        ></el-breadcrumb-item
      >
    </el-breadcrumb>
    <!-- 发布文章 -->
    <div class="public_form">
      <el-form ref="form" :model="post_data" label-width="80px">
        <!-- 标题 -->
        <el-form-item label="标题：">
          <el-input v-model="post_data.title"></el-input>
        </el-form-item>

        <!-- 类型 -->
        <el-form-item label="类型：">
          <el-radio-group v-model="post_data.type">
            <el-radio :label="1" border>文章</el-radio>
            <el-radio :label="2" border>视频</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 内容 -->
        <el-form-item label="内容：">
          <!-- Type1 富文本框 -->
          <VueEditor
            :config="config"
            v-if="post_data.type == 1"
            ref="vueEditor"
          />
          <!-- Type2 文件上传 -->
          <el-upload
            class="upload-demo"
            v-if="post_data.type == 2"
            action="http://localhost:3000/upload"
            :headers="getToken()"
            :on-success="onSuccess"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            multiple
            :limit="3"
            :on-exceed="handleExceed"
            :file-list="fileList"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">请上传视频文件</div>
          </el-upload>
        </el-form-item>

        <!-- 栏目 -->
        <el-form-item label="栏目：">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0"></div>
          <el-checkbox-group
            v-model="post_data.categories"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="item in cities"
              :label="item.id"
              :key="item.id"
              >{{ item.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>

        <!-- 封面 -->
        <el-form-item label="封面：">
          <el-upload
            action="http://localhost:3000/upload"
            :headers="getToken()"
            :on-success="handlePoster"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>

        <!-- 按钮：发布文章 -->
        <el-button type="primary" @click="publicPost">发布文章</el-button>
      </el-form>
    </div>
  </div>
</template>

<script>
// 富文本框组件
import VueEditor from "vue-word-editor";
import "quill/dist/quill.snow.css";

// get_category(get栏目列表) 、 public_post(发布文章)
import { get_category, public_post } from "@/apis/post.js";

export default {
  // 注册组件
  components: {
    VueEditor,
  },
  //   数据
  data() {
    return {
      //文章参数对象：
      post_data: {
        title: "", //文章标题
        content: "", //文章内容
        categories: [], //所属栏目ID集合
        cover: [], //封面图片ID集合
        type: 1, //1为文章，2为视频
      },

      // 富文本框的配置
      config: {
        // 上传图片的配置
        uploadImage: {
          url: "http://localhost:3000/upload",
          name: "file",
          headers: this.getToken(), //传递表头
          // res是结果，insert方法会把内容注入到编辑器中，res.data.url是资源地址
          uploadSuccess(res, insert) {
            //  console.log(res);
            insert("http://localhost:3000" + res.data.data.url);
          },
        },

        // 上传视频的配置
        uploadVideo: {
          url: "http://localhost:3000/upload",
          name: "file",
          headers: this.getToken(), //传递表头
          uploadSuccess(res, insert) {
            insert("http://localhost:3000" + res.data.data.url);
          },
        },
      },

      // 上传文件
      fileList: [],

      // 栏目：
      checkAll: false, //全选/全不选
      checkedCities: ["上海", "北京"], //已选项
      cities: [], //所有选择项
      isIndeterminate: true, //不确定的

      // 封面：
      dialogImageUrl: "",
      dialogVisible: false,
    };
  },
  //   方法
  methods: {
    //   获取本地admin_tokon
    getToken() {
      return {
        Authorization: localStorage.getItem("admin_tokon"),
      };
    },

    //  获取栏目列表, 并传给复选框数组cities
    async get_category() {
      let res = await get_category();
      // console.log(res);
      if (res.status == 200) {
        this.cities = res.data.data;
        //   删掉数组中的 关注和头条
        this.cities.forEach((item, index) => {
          if (item.name == "关注") {
            this.cities.splice(index, 1);
          }
        });
        this.cities.forEach((item, index) => {
          if (item.name == "头条") {
            this.cities.splice(index, 1);
          }
        });
      }
      // console.log(this.cities);
    },

    //   文件上传：
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    onSuccess(response) {
      console.log(response);
      if (response.message == "文件上传成功") {
        this.post_data.content = response.data.url;
      }
    },

    //  栏目：
    handleCheckAllChange(val) {
      this.post_data.categories = val
        ? this.cities.map((v) => {
            return v.id;
          })
        : [];

      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      console.log(value);
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cities.length;
    },

    //  封面：
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handlePoster(response, file, fileList) {
      // console.log(response);
      // 将成功后的图片ID以键值对的姿态加到cover数组中
      this.post_data.cover.push({ id: response.data.id });
    },

    ///////////////////

    // 发布文章
    async publicPost() {
      //  改造数据： 把数组 里的值 改成键值对 的 对象
      this.post_data.categories = this.post_data.categories.map((v) => {
        return { id: v };
      });
      // console.log(this.post_data.categories);
      if (this.post_data.type == 1) {
        // 富文本框中的内容  赋予文章content
        this.post_data.content = this.$refs.vueEditor.editor.root.innerHTML;
      }
      console.log(this.post_data);
      let res = await public_post(this.post_data);
      console.log(res);
      if (res.status == 200) {
        this.$message({
          message: res.data.message,
          type: "success",
          duration: 2000,
          center: true,
        });
        setTimeout(() => {
          this.$router.push({ path: "articleList" });
        }, 600);
      } else {
        this.$message({
          message: res.data.message,
          type: "error",
          duration: 2000,
          center: true,
        });
      }
    },
  },
  //   钩子：
  mounted() {
    this.get_category();
  },
};
</script>

// 样式
<style lang="less" scoped>
.mianbaoxie {
  margin-bottom: 20px;
}
.public_form {
  box-shadow: 0 0 6px 0 #e9e9e9e9;
  padding: 20px;
  text-align: left;
}
</style>